package com.demo.apparel.service.uniapp.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.apparel.entity.OrderItem;
import com.demo.apparel.entity.Orders;
import com.demo.apparel.mapper.uniapp.OrderItemMapper;
import com.demo.apparel.mapper.uniapp.OrdersMapper;
import com.demo.apparel.service.uniapp.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    /**
     * 创建订单
     * @param userId 用户ID
     * @param totalPrice 总金额
     * @param orderItems 订单商品信息
     * @return 创建的订单
     */
    @Override
    @Transactional
    public Orders createOrder(String userId, BigDecimal totalPrice, List<OrderItem> orderItems) {
        String orderId = UUID.randomUUID().toString().replace("-", "");

        Orders order = new Orders();
        order.setId(orderId);
        order.setUserId(userId);
        order.setTotalPrice(totalPrice);
        order.setStatus("UNPAID");
        order.setCreatedTime(LocalDateTime.now());
        order.setUpdatedTime(LocalDateTime.now());

        ordersMapper.insert(order);

        for (OrderItem item : orderItems) {
            item.setOrderId(orderId);
            item.setId(UUID.randomUUID().toString().replace("-", ""));
            orderItemMapper.insert(item);
        }

        return order;
    }

    /**
     * 更新订单状态为已支付
     * @param orderId 订单ID
     */
    @Override
    public void updateOrderStatusToPaid(String orderId) {
        Orders order = new Orders();
        order.setId(orderId);
        order.setStatus("PAID");
        ordersMapper.updateById(order);
    }

    /**
     * 更新订单状态为待支付
     * @param orderId 订单ID
     */
    @Override
    public void updateOrderStatusToUnpaid(String orderId) {
        Orders order = new Orders();
        order.setId(orderId);
        order.setStatus("UNPAID");
        ordersMapper.updateById(order);
    }

    /**
     * 查询用户的订单列表
     * @param userId 用户ID
     * @return 订单列表
     */
    @Override
    public List<Orders> getUserOrders(String userId) {
        return ordersMapper.selectByUserId(userId);
    }

    /**
     * 查询订单详情
     * @param orderId 订单ID
     * @return 订单详情
     */
    @Override
    public Orders getOrderById(String orderId) {
        return ordersMapper.selectById(orderId);
    }

    /**
     * 处理支付
     * @param orderId 订单ID
     * @param paymentMethod 支付方式
     * @param transactionId 支付交易号
     * @return 支付结果
     */
    @Override
    @Transactional
    public boolean processPayment(String orderId, String paymentMethod, String transactionId) {
        // 先查询订单
        Orders order = ordersMapper.selectById(orderId);
        if (order == null || !order.getStatus().equals("UNPAID")) {
            return false; // 订单不存在或者不是待支付状态
        }
        // 假设支付过程已经通过支付接口完成，这里模拟支付成功
        // 更新支付信息
        order.setStatus("PAID");
        order.setPaymentMethod(paymentMethod);
        order.setPaymentTransactionId(transactionId);
        order.setPaymentTime(LocalDateTime.now());

        // 更新订单状态
        ordersMapper.updateById(order);

        return true;
    }

    /**
     * 模拟支付成功
     * @param orderId 订单ID
     * @param paymentTransactionId 支付交易号
     * @return 支付结果
     */
    @Override
    public boolean simulatePaymentSuccess(String orderId, String paymentTransactionId) {
        // 查询订单
        Orders order = ordersMapper.selectById(orderId);
        if (order == null || !order.getStatus().equals("UNPAID")) {
            return false;
        }

        // 模拟支付成功
        order.setStatus("PAID");
        order.setPaymentMethod("SIMULATED_PAYMENT");
        order.setPaymentTransactionId(paymentTransactionId);
        order.setPaymentTime(LocalDateTime.now());

        // 更新订单状态
        ordersMapper.updateById(order);

        return true;
    }

    // 生成支付交易号并存入数据库
    @Override
    public String generatePaymentTransactionId(String orderId) {
        // 为订单生成唯一的交易号
        String paymentTransactionId = UUID.randomUUID().toString().replace("-", "");

        // 查找订单
        Orders order = ordersMapper.selectById(orderId);
        if (order == null) {
            return null;  // 如果订单不存在，返回null
        }

        // 设置交易号并更新订单
        order.setPaymentTransactionId(paymentTransactionId);
        ordersMapper.updateById(order);

        return paymentTransactionId;
    }

    // 取消订单
    @Override
    @Transactional
    public boolean cancelOrder(String orderId) {
        Orders order = ordersMapper.selectById(orderId);
        if (order == null || order.getStatus().equals("PAID")) {
            // 如果订单不存在或已经支付，无法取消
            return false;
        }

        // 将订单状态更新为已取消
        order.setStatus("CANCELLED");
        ordersMapper.updateById(order);

        return true;
    }

    // 删除超时未支付订单
    @Override
    @Scheduled(cron = "0 0 * * * ?")
    public void deleteExpiredOrders() {
        System.out.println("定时任务已触发");  // 这行用来确认定时任务是否触发 minusHours minusMinutes
        LocalDateTime expirationTime = LocalDateTime.now().minusHours(1);
        System.out.println("查询的过期时间为: " + expirationTime);
        List<Orders> expiredOrders = ordersMapper.selectUnpaidOrdersOlderThan(expirationTime);
        System.out.println("查询到的超时未支付订单: " + expiredOrders.size());
        for (Orders order : expiredOrders) {
            System.out.println("准备删除订单ID: " + order.getId());
            ordersMapper.deleteById(order.getId());
            orderItemMapper.deleteByOrderId(order.getId());
            System.out.println("订单 " + order.getId() + " 已成功删除");
        }
    }

    // 发起支付接口，模拟第三方支付请求
    @Override
    public boolean initiatePayment(String orderId, BigDecimal amount) {
        // 这里可以调用第三方支付平台的API
        // 假设发起支付请求成功，返回true
        // 例如，调用微信支付或支付宝API发起支付
        // 模拟支付请求成功
        return true;
    }

}
